<?php

namespace app\admin\controller;

class RoleBase
{
    public function index()
    {
        $query = \app\model\Role::field(['id', 'name', 'created_at'])->with(['menus'])->order('id', 'desc');

        if ($name = input('name')) {
            $query->where('name', $name);
        }

        $models = $query->select();

        return json(['code' => 20000, 'data' => ['roles' => $models]]);
    }

    public function delete()
    {
        $model = \app\model\Role::destroy(input('id'));

        return json(['code' => 20000, 'msg' => '移除成功', 'data' => $model]);
    }

    public function update()
    {
        $model = \app\model\Role::update(input());

        $model = \app\model\Role::find($model->id);

        if ($menus = input('menus')) {
            $model->menus()->sync(array_column($menus, 'id'));
        }

        return json(['code' => 20000, 'msg' => '更新成功', 'data' => $model]);
    }

    public function create()
    {
        $param = request()->param();

        $model = \app\model\Role::create($param);

        if (!$model) {
            return json(['code' => 40400, 'msg' => '新增失败']);
        }

        if ($menus = input('menus')) {
            $model->menus()->sync(array_column($menus, 'id'));
        }

        return json(['code' => 20000, 'msg' => '新增成功', 'data' => $model]);
    }

    public function detail()
    {
        $model = \app\model\Role::field('id', 'name')->where('id', input('id'))->find();

        return ['code' => 20000, 'data' => ['role' => $model]];
    }
}
